<?php
/**
 * Info.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-19
 * Time: 13:59
 */

namespace App\Http\Controllers\Api\Customer;


use App\Exceptions\RunException;
use App\Http\Controllers\Base;
use App\Tables;

class Info extends Base
{
    public function getDebt()
    {
        $id = (int) $this->request->get('id', 0);
        if($id <= 0) {
            return $this->responseSuccess(0);
        }
        return $this->responseSuccess(Tables\Order::getDebt($id));
    }

    public function getList()
    {
        $name = $this->request->get('name', '');
        $type = (int) $this->request->get('type', 0);

        $id   = $this->request->get('id');
        $id = is_array($id) ? (array) $id : (empty($id) ? null : [(int) $id]);

        $customerTable = Tables\Customer::query();
        if(!empty($name)) {
            $customerTable->where('name', $name);
        }
        if($type > 0) {
            $customerTable->where('type', $type);
        }
        if(!empty($id)) {
            $customerTable->whereIn('id', $id);
        }

        $all = $customerTable->get();
        $r = [];
        foreach($all  as $v) {
            $address = [];
            $contacts = [];
            $adList = $v->address;
            foreach($adList as $k => $vv) {
                $address[] = [
                    'id' => $vv['id'], 'name' => $vv['name'], 'primary' => $vv['primary'] == 1
                ];
            }
            $ctList = $v->contacts;
            foreach($ctList as $k => $vv) {
                $contacts[] = [
                    'id' => $vv['id'], 'name' => $vv['name'],'phoneNumber'=> $vv['phone_number'],
                    'primary' => $vv['primary'] == 1
                ];
            }

            $r[] = [
                'id' => $v['id'], 'name' => $v['name'], 'type' => $v['type'],
                'pyCode' => $v['py_code'], 'remark' => $v['remark'],
                'address' => $address,
                'contacts' => $contacts
            ];
        }

        return $this->responseSuccess($r);
    }

    public function get()
    {
        $id = (int) $this->request->get('id', 0);
        if($id <= 0 ) {
            return $this->responseSuccess();
        }
        $customer = Tables\Customer::find($id);
        if(empty($customer)) {
            return $this->responseSuccess();
        }
        $contacts = $address = [];
        $adList = $customer->address;
        $ctList = $customer->contacts;

        foreach($adList as $k => $v) {
            $address[] = [
                'id' => $v['id'], 'name' => $v['name'], 'primary' => $v['primary'] == 1
            ];
        }
        foreach($ctList as $k => $v) {
            $contacts[] = [
                'id' => $v['id'], 'name' => $v['name'],'phoneNumber'=> $v['phone_number'],
                'primary' => $v['primary'] == 1
            ];
        }


        return $this->responseSuccess([
            'id' => $customer['id'], 'name' => $customer['name'], 'pyCode' => $customer['py_code'],
            'type' => $customer['type'], 'salesman' => $customer['salesman'], 'salesmanId' => $customer['salesman_id'],
            'qq' => $customer['qq'], 'wx' => $customer['wx'],'remark' => $customer['remark'],'coordinate' => $customer['coordinate'],
            'address'=> $address,
            'contacts' => $contacts

        ]);
    }

    public function add()
    {
        $name       = $this->request->post('name');
        $pyCode     = $this->request->post('pyCode');
        $type       = (int) $this->request->post('type', 0);
        $salesman   = $this->request->post('salesman', '');
        $salesmanId = (int) $this->request->post('salesmanId', 0);
        $address    = (array) $this->request->post('address');
        $addressPrimaryIndex = (int) $this->request->post('addressPrimaryIndex', 0);
        $coordinate = $this->request->post('coordinate');
        $contacts   = (array) $this->request->post('contacts');
        $contactsPrimaryIndex = (int) $this->request->post('contactsPrimaryIndex', 0);
        $qq         = (int) $this->request->post('qq', 0);
        $wx         = $this->request->post('wx');
        $remark     = $this->request->post('remark');

        if(empty($name)) {
            return $this->responseFail('名称不能为空');
        }

        if($type <= 0) {
            return $this->responseFail('请选择客户类型');
        }

        \DB::beginTransaction();
        try {
            $addTime = time();
            $insertData = [
                'name' => $name,
                'py_code' => $pyCode,
                'type' => $type,
                'salesman' => $salesman,
                'salesman_id' => $salesmanId,
                'coordinate' => $coordinate,
                'qq' => $qq,
                'wx' => $wx,
                'remark' => $remark,
                'add_time' => $addTime,
            ];
            $cid = (int) Tables\Customer::insertGetId($insertData);
            if($cid <= 0) {
                throw new RunException('增加失败(1)');
            }
            $insertData = [];

            foreach($address as $k =>  $ad) {
                if(empty($ad['name'])) { continue;}
                $insertData[] = [
                    'cid' => $cid,
                    'name' => $ad['name'],
                    'primary' => $k === $addressPrimaryIndex ? 1 : 0,
                    'add_time' => $addTime
                ];
            }
            if(!empty($insertData)) {
                $ok = (bool) Tables\CustomerAddress::insert($insertData);
                if(!$ok) {
                    throw new RunException('增加失败(2)');
                }
            }

            $insertData = [];

            foreach($contacts as $k => $ct) {
                if(empty($ct['name']) and empty($ct['phoneNumber'])) { continue; }
                $insertData[] = [
                    'cid' => $cid,
                    'name' => $ct['name'],
                    'phone_number' => $ct['phoneNumber'],
                    'primary' => $k === $contactsPrimaryIndex ? 1: 0,
                    'add_time' => $addTime
                ];
            }
            if(!empty($insertData)) {
                $ok = (bool) Tables\CustomerContacts::insert($insertData);
                if(!$ok) {
                    throw new RunException('增加失败(2)');
                }
            }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e->getMessage());
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function update()
    {
        $id         = (int) $this->request->post('id', 0);
        $name       = $this->request->post('name');
        $pyCode     = $this->request->post('pyCode');
        $type       = (int) $this->request->post('type', 0);
        $address    = (array) $this->request->post('address');
        $addressPrimaryIndex = (int) $this->request->post('addressPrimaryIndex', 0);
        $coordinate = $this->request->post('coordinate');
        $contacts   = (array) $this->request->post('contacts');
        $contactsPrimaryIndex = (int) $this->request->post('contactsPrimaryIndex', 0);
        $qq         = (int) $this->request->post('qq', 0);
        $wx         = $this->request->post('wx');
        $remark     = $this->request->post('remark');

        if($id <= 0) {
            return $this->responseFail('无数据');
        }

        if(empty($name)) {
            return $this->responseFail('名称不能为空');
        }

        if($type <= 0) {
            return $this->responseFail('请选择客户类型');
        }

        \DB::beginTransaction();
        try {
            $addTime = time();
            $updateData = [
                'name' => $name,
                'py_code' => $pyCode,
                'type' => $type,
                'coordinate' => $coordinate,
                'qq' => $qq,
                'wx' => $wx,
                'remark' => $remark,
                'update_time' => date('Y-m-d H:i:s')
            ];
            $customer = Tables\Customer::find($id);
            if(empty($customer)) {
                throw new RunException('找不到数据');
            }

            $ok = (bool) Tables\Customer::where('id', $id)->update($updateData);
            if(!$ok) {
                throw new RunException('修改失败(1)');
            }
            $updateData = [];
            foreach($address as $k =>  $ad) {
                if(empty($ad['name'])) { continue;}
                $updateData[] = [
                    'cid' => $id,
                    'name' => $ad['name'],
                    'primary' => $k === $addressPrimaryIndex ? 1 : 0,
                    'add_time' => $addTime
                ];
            }
            if(!empty($updateData)) {
                Tables\CustomerAddress::where('cid', $id)->delete();
                $ok = (bool) Tables\CustomerAddress::insert($updateData);
                if(!$ok) {
                    throw new RunException('修改失败(2)');
                }
            }

            $updateData = [];

            foreach($contacts as $k => $ct) {
                if(empty($ct['name']) and empty($ct['phoneNumber'])) { continue; }
                $updateData[] = [
                    'cid' => $id,
                    'name' => $ct['name'],
                    'phone_number' => $ct['phoneNumber'],
                    'primary' => $k === $contactsPrimaryIndex ? 1: 0,
                    'add_time' => $addTime
                ];
            }
            if(!empty($updateData)) {
                Tables\CustomerContacts::where('cid', $id)->delete();
                $ok = (bool) Tables\CustomerContacts::insert($updateData);
                if(!$ok) {
                    throw new RunException('修改失败(2)');
                }
            }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e->getMessage());
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function del()
    {
        $id = (int) $this->request->post('id', 0);
        if($id <= 0) {
            return $this->responseFail('未找到数据！');
        }

        \DB::beginTransaction();
        try {
            $customer = Tables\Customer::find($id);
            if(empty($customer)) {
                throw new RunException('删除失败(1)');
            }
            $count = Tables\Order::query()
                ->whereRaw('(make_status!=1 or delivery_status!=1 or pay_status!=1)')
                ->where('customer_id', $id)
                ->where('dumped', Tables\Order::No_Dumped)
                ->count();
            if($count > 0) {
                throw new RunException('有正在进行中的订单，无法删除！');
            }

            foreach($customer->address as $ad) {
                $ok = (bool) $ad->delete();
                if(!$ok) {
                    throw new RunException('删除失败(2)');
                }
            }
            foreach($customer->contacts as $ct) {
                $ok = (bool) $ct->delete();
                if(!$ok) {
                    throw new RunException('删除失败(3)');
                }
            }

            $ok = $customer->delete();
            if(!$ok) {
                throw new RunException('删除失败(4)');
            }
            \DB::commit();

        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e->getMessage());
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }
}